<template>
  <!-- 取消结算 -->
  <div class="vehicle-details-wrap">
    <ButtonArea :style="{ paddingLeft: '0px' }">
      <AjaxButton type="primary" icon="el-icon-folder" :disabled="canCancel" :click="cancelBalance">取消结算</AjaxButton>
      <el-button type="primary" icon="el-icon-refresh-left" :disabled="false" @click="resetForm">取消</el-button>
    </ButtonArea>
    <!-- 工单信息 -->
    <div class="box">
      <FormPanel ref="feesSettlementPanel" :list="feesSettlementList" :cols="4" :labelWidth="90" :isSubmitBtn="false" @formChange="feesSettlementChangeHandle" />
    </div>
    <!-- 会员信息 -->
    <div class="box">
      <FormPanel ref="vipPanel" :list="vipList" :cols="4" :labelWidth="90" :isSubmitBtn="false" />
    </div>
    <!-- 工单详情 -->
    <div class="left">
      <div :style="{ paddingLeft: '10px', minHeight: '200px' }">
        <LazyLoadTab v-model="orderPartName" :tabMenus="orderPartMenus"></LazyLoadTab>
        <LazyLoadTab v-model="repairPartName" :tabMenus="repairPartMenus"></LazyLoadTab>
        <LazyLoadTab v-model="receivablesName" :tabMenus="receivablesMenus" @tab-click="tabClickHandle"></LazyLoadTab>
      </div>
    </div>
    <!-- 合计金额信息 -->
    <div class="right">
      <FormPanel ref="otherInfoPanel" :list="otherInfoList" :cols="1" :labelWidth="110" :isSubmitBtn="false" @formChange="otherInfoChangeHandle" />
    </div>

    <!-- 选择弹窗 -->
    <BaseDialog title="工单选择" :visible.sync="orderNoDialogShow" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <searchBalance
        :WorkSearch_rono="WorkSearch_rono"
        :WorkSearch_partno="WorkSearch_partno"
        @close="
          val => {
            this.orderNoDialogShow = val;
          }
        "
        @selectRow="partRowSelect"
      />
    </BaseDialog>

    <BaseDialog title="销售单选择" :visible.sync="saleOrderSelectVisible" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <searchSaleOrder :WorkSearch_rono="WorkSearch_rono" :WorkSearch_partno="WorkSearch_partno" @close="saleOrderSelectVisible = false" @selectRow="partRowSelect"></searchSaleOrder>
    </BaseDialog>

    <BaseDialog title="选择装饰派工单" :visible.sync="boutiqueOrderNoDialogShow" width="70%" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <boutiqueSearch
        :WorkSearch_billno="WorkSearch_billno"
        @selectRow="boutiqueOrderRowSelect"
        @close="
          val => {
            this.boutiqueOrderNoDialogShow = val;
          }
        "
      />
    </BaseDialog>
  </div>
</template>

<script>
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import { isEmpty, sleep, arrayObjDeWeight } from '@/utils/index';
import searchBalance from './searchBalance';
import boutiqueSearch from './boutiqueSearch';
import searchSaleOrder from './searchSaleOrder';
import {
  cancelBalance,
  getBalanceDetail,
  getLabourDetail,
  queryRoRepairPartByBalanceNo,
  querySalesPo,
  getAddPo,
  queryPayObjPo,
  findNoList,
  pushHx,
  queryVipInfoByRono,
  systemLogForCancelBalance,
  cancelSettlementOther,
  queryVipInfoByBillNo
} from '@/api/finance/repairFinance/cancelFinance';
import { getStatusByRoNo, updateLastDate, checkClaimStatusByRoNo, getMemberNOByNo } from '@/api/finance/repairFinance/cancelFinance';
import { getOtherData } from '@/api/repair/repairReception/feesSettlement';

import { queryBillItemByBillNO, queryBillPartByBillNO } from '@/api/repair/repairReception/feesSettlement';
import { findInvoiceType } from '@/api/finance/advancesReceived/register';
import { queryDiscountMode } from '@/api/repair/repairReception/feesSettlement';
import { getSystemDefault } from '@/api/repair/repairReception/customer';
import { mapActions } from 'vuex';
import { isAuthorized } from '@/utils/index';
export default {
  name: 'cancelBalance',
  components: {
    searchBalance,
    boutiqueSearch,
    searchSaleOrder
  },
  mixins: [dictionary],
  data() {
    this.dmsFunc = { dmsFuncId: 55100010 };
    this.config = {
      defaultType: 'default'
    };
    // this.receivablesList = [];
    return {
      feesSettlementList: this.createFeesSettlementList(),
      otherInfoList: this.createOtherInfoList(),
      orderPartName: '工单',
      orderPartMenus: this.createOrderPartMenus(),
      repairPartName: '维修项目',
      repairPartMenus: this.createRepairPartMenus(),
      receivablesName: '实收',
      receivablesMenus: this.createReceivablesMenus(),
      orderNoDialogShow: false,
      saleOrderSelectVisible: false, // 是否显示销售单选择弹窗
      WorkSearch_billno: '',
      boutiqueOrderNoDialogShow: false,
      vipList: this.createVipFormList(),
      canCancel: true,
      receiveAmount: 0,
      orderType: 0, // 选择类型
      balanceInfo: [],
      WorkSearch_rono: '',
      WorkSearch_partno: '',
      is_auth: false,
      orderStatus: {}
    };
  },
  mounted() {
    // this.findInvoiceCodeFun();
    this.queryDiscountModeFun();
    this.getAuth();
    this.systemDefalutParams();
  },
  methods: {
    ...mapActions('app', ['refreshView']),
    getAuth() {
      // 是否可以关闭工单
      if (isAuthorized('1314', '13141009')) {
        this.is_auth = true;
      } else {
        this.is_auth = false;
      }
    },
    createFeesSettlementList() {
      return [
        {
          type: 'INPUT',
          label: '工单号',
          fieldName: 'RO_NO',
          readonly: false,
          unitRender: () => {
            return <el-button icon="el-icon-tickets" onClick={this.openOrderNoHandle}></el-button>;
          },
          onEnter: val => {
            // this.WorkSearch_rono = val;
            this.openOrderNoHandle();
          },
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'LICENSE',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '原结算单号',
          fieldName: 'BALANCE_NO',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '结算单号',
          fieldName: 'NEW_BALANCE_NO',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '备件销售单号',
          fieldName: 'SALES_PART_NO',
          readonly: false,
          unitRender: () => {
            return <el-button icon="el-icon-tickets" onClick={this.openPartNoHandle}></el-button>;
          },
          onEnter: val => {
            // this.WorkSearch_partno = val;
            this.openPartNoHandle();
          },
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'REMARK',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '备注1',
          fieldName: 'REMARK1',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '故障描述',
          fieldName: 'RO_TROUBLE_DESC',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '装饰工单号',
          fieldName: 'BILL_NO',
          readonly: false,
          unitRender: () => {
            return <el-button icon="el-icon-tickets" onClick={this.openBoutiqueNoHandle}></el-button>;
          },
          onEnter: val => {
            // this.WorkSearch_rono = val;
            this.openBoutiqueNoHandle();
          },
          placeholder: '请选择...'
        }
      ];
    },
    createOtherInfoList() {
      return [
        {
          type: 'SELECT',
          label: '优惠模式',
          fieldName: 'DISCOUNT_MODE_CODE',
          placeholder: '请选择',
          disabled: true,
          filterable: true,
          itemList: []
        },
        {
          type: 'SELECT',
          label: '付款方式',
          fieldName: 'PAY_TYPE_CODE',
          placeholder: '请选择',
          disabled: true,
          itemList: this.createDictList('8044'),
          rules: [{ required: false, message: '请选择付款方式', trigger: 'change' }]
        },
        {
          type: 'CHECKBOX',
          label: '是否欠款结算',
          fieldName: 'ARR_BALANCE',
          disabled: true,
          options: {
            trueValue: 10041001,
            falseValue: 10041002
          }
        },
        {
          type: 'INPUT',
          label: '担保方',
          fieldName: 'GUARANTOR',
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '欠收金额',
          fieldName: 'ARREARS_AMOUNT',
          disabled: true
        },
        {
          type: 'CHECKBOX',
          label: '是否使用预存金',
          fieldName: 'USED_MEMBER',
          disabled: true,
          initialValue: 0
        },
        {
          type: 'INPUT',
          label: '预存金使用总金额',
          fieldName: 'DEPOSIT_AMOUNT',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '优惠券使用总金额',
          fieldName: 'COUPON_AMOUNT',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '其他金额1',
          fieldName: 'OTHER1_AMOUNT',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '其他金额2',
          fieldName: 'OTHER2_AMOUNT',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '其他金额3',
          disabled: true,
          fieldName: 'OTHER3_AMOUNT'
        },
        {
          type: 'SELECT',
          label: '包工方式',
          fieldName: 'BG_TYPE',
          disabled: true,
          itemList: this.createDictList('8145'),
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '包工费',
          disabled: true,
          fieldName: 'BGF',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '材料服务费',
          disabled: true,
          fieldName: 'CLFWF',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '辅材费',
          disabled: true,
          fieldName: 'FCF',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '施救费',
          fieldName: 'SJF',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '应收总金额',
          fieldName: 'SUM_AMOUNT',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '实收总金额',
          fieldName: 'REAL_TOTAL_AMOUNT',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '税率',
          fieldName: 'TAX',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '税额',
          fieldName: 'TAX_AMOUNT',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '不含税金额',
          fieldName: 'NET_AMOUNT',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '索赔成本',
          fieldName: 'CLAIM_COST',
          initialValue: '',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '去零金额',
          fieldName: 'SUB_OBB_AMOUNT',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '合计优惠金额',
          fieldName: 'discountAmount',
          initialValue: '',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '合计金额',
          fieldName: 'TOTAL_AMOUNT',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '现金收款',
          fieldName: 'RECEIVE_AMOUNT',
          disabled: true
        }

        // {
        //   type: 'INPUT',
        //   label: '总金额',
        //   fieldName: 'TOTAL_AMOUNT',
        //   disabled: true
        // },
        // {
        //   type: 'INPUT',
        //   label: '收款金额',
        //   fieldName: 'RECEIVE_AMOUNT',
        //   disabled: true
        // },
      ];
    },
    createOrderPartMenus() {
      return [
        {
          title: '工单',
          path: 'repair/repairReception/feesSettlement/orderList/index',
          params: {
            data: {},
            formPage: 'cancelFinance'
          },
          on: {
            changeList(val) {}
          }
        },
        {
          title: '备件销售单',
          path: 'repair/repairReception/feesSettlement/partsSaleOrder/index',
          params: {
            data: {}
          },
          on: {
            changeList(val) {}
          }
        },
        {
          title: '装饰派工单',
          path: 'repair/repairReception/feesSettlement/boutiqueOrder/index',
          params: {
            data: {}
          },
          on: {
            changeList(val) {}
          }
        }
      ];
    },
    createRepairPartMenus() {
      return [
        {
          title: '维修项目',
          path: 'finance/repairFinance/cancelFinance/repair/maintenanceProject',
          params: {
            list: [],
            resetTable: false
          },
          on: {
            changeList(val) {}
          }
        },
        {
          title: '维修材料',
          path: 'finance/repairFinance/cancelFinance/repair/maintenanceMaterials',
          params: {
            list: [],
            resetTable: false
          },
          on: {
            changeList(val) {}
          }
        },
        {
          title: '销售材料',
          path: 'finance/repairFinance/cancelFinance/repair/salesMaterials',
          params: {
            list: [],
            resetTable: false
          },
          on: {
            changeList(val) {}
          }
        },
        {
          title: '附加项目',
          path: 'finance/repairFinance/cancelFinance/repair/additionalItems',
          params: {
            list: [],
            resetTable: false
          },
          on: {
            changeList(val) {}
          }
        },
        {
          title: '装饰项目',
          path: 'finance/repairFinance/cancelFinance/repair/boutiqueProject',
          params: {
            list: [],
            resetTable: false
          },
          on: {
            changeList(val) {}
          }
        },
        {
          title: '装饰材料',
          path: 'finance/repairFinance/cancelFinance/repair/boutiquePart',
          params: {
            list: [],
            resetTable: false
          },
          on: {
            changeList(val) {}
          }
        }
      ];
    },
    createReceivablesMenus() {
      return [
        {
          title: '应收',
          path: 'repair/repairReception/feesSettlement/receivables/receivable',
          params: {
            list: [],
            resetTable: false
          },
          on: {
            changeList(val) {}
          }
        },
        {
          title: '实收',
          path: 'finance/repairFinance/cancelFinance/netReceipts',
          params: {
            list: [],
            resetTable: false
          },
          on: {
            changeList(val) {}
          }
        }
      ];
    },
    createVipFormList() {
      return [
        {
          type: 'INPUT',
          label: '会员卡号',
          fieldName: 'vCardNo',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '卡内余额',
          fieldName: 'nValideAmt',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '本次积分',
          fieldName: 'nThisPoint',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '积分余额',
          fieldName: 'nCardPoint',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '工时优惠率',
          fieldName: 'nManhaurDisRate',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '材料优惠率',
          fieldName: 'nMaterialDisrate',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '固定积分',
          fieldName: 'nPoint',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '积分比例',
          fieldName: 'nRatioPoint',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '积分倍数',
          fieldName: 'nRatioScore',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '辅卡积分比例',
          fieldName: 'nPointPer',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '优惠充值',
          fieldName: 'nCardRecharge',
          hidden: true,
          disabled: true
        },
        {
          type: 'INPUT',
          label: '现金优惠',
          fieldName: 'nMoneyRecharge',
          hidden: true,
          disabled: true
        }
        // {
        //   type: 'CHECKBOX',
        //   label: '使用会员卡',
        //   fieldName: 'isUsedCard',
        //   options: {
        //     trueValue: 10041001,
        //     falseValue: 10041002
        //   }
        // }
      ];
    },
    // 获取发票信息
    // async findInvoiceCodeFun() {
    //   const res = await findInvoiceType(this.dmsFunc);
    //   res.data.map(x => {
    //     this.otherInfoList[1].itemList.push({ value: x.INVOICE_TYPE_CODE, text: x.INVOICE_TYPE_NAME });
    //   });
    // },
    // 获取优惠模式
    async queryDiscountModeFun() {
      const res = await queryDiscountMode();
      let resData = arrayObjDeWeight(res.data, 'DISCOUNT_MODE_CODE'); // 前端去重 消除报错
      this.otherInfoList.find(item => item.fieldName === 'DISCOUNT_MODE_CODE').itemList = resData.map(x => ({ text: x.DISCOUNT_MODE_NAME, value: x.DISCOUNT_MODE_CODE }));
    },
    // 工单选择点击确定
    partRowSelect(row) {
      console.log(row, '--------row');
      if (!row) {
        return;
      }
      if (row.SALES_PART_NO !== '' && (row.RO_NO === '' || row.RO_NO === null)) {
        this.orderPartName = '备件销售单';
        this.repairPartName = '销售材料';
        this.orderType = 2;
      } else {
        this.orderPartName = '工单';
        this.repairPartName = '维修项目';
        this.orderType = 1;

        this.orderPartMenus[0].params.data = Object.assign(this.orderPartMenus[0].params.data, row);
        console.log('赋值工单字段', this.orderPartMenus[0].params.data);
        this.getOther(row.VIN);
      }

      // 表单赋值
      this.feesSettlementList.find(item => item.fieldName === 'RO_NO').initialValue = row.RO_NO;
      this.feesSettlementList.find(item => item.fieldName === 'BALANCE_NO').initialValue = row.BALANCE_NO;
      this.feesSettlementList.find(item => item.fieldName === 'SALES_PART_NO').initialValue = row.SALES_PART_NO;
      this.feesSettlementList.map(item => {
        item.initialValue = row[item.fieldName];
        console.log(item);
      });
      // 工单号不为空
      if (row.RO_NO) {
        this.getLabourDetailFun(row); // 维修项目
        this.getRoRepairPartByBalanceNoFun(row); // 维修材料
        this.getAddPoFun(row); // 附加项目
        this.queryVipCartInfo(row, 1); // 会员卡信息
      }

      // 销售单号不为空
      if (row.SALES_PART_NO) {
        // 销售材料
        this.getSalesPoFun(row);
        this.queryVipCartInfo(row, 2);
      }

      // 结算单号不为空
      if (row.BALANCE_NO) {
        this.getBalanceDetailFun(row);
        this.getPayObjPo(row);
      }
      this.canCancel = false;
    },
    // 装饰派工单号点击确定
    boutiqueOrderRowSelect(row) {
      if (!row) {
        return;
      }

      // 折扣不显示
      console.log(row, 'row Data');

      row.SERVICE_ADVISOR = Number(row.SERVICE_ADVISOR);
      this.orderPartName = '装饰派工单';
      this.repairPartName = '装饰项目';
      // this.printData = row;
      // this.printData.type = 'billNo';
      this.BILL_NO = row.BILL_NO;
      this.orderType = 3;
      this.boutiqueOrderNoDialogShow = false;

      // 给页面上的内容赋值
      this.feesSettlementList.map(item => {
        item.initialValue = row[item.fieldName];
      });

      // 如果存在装饰派工单号，查询销售材料等相关信息
      if (row.BILL_NO) {
        row['CUSTOMER_NO'] = row.CUSTOMER_NO;
        row['CUSTOMER_NAME'] = row.CUSTOMER_NAME;
        // 给页面上的内容赋值
        this.orderPartMenus[2].params.data = row;
      }

      // 查询应收实收数据,左侧结算详情数据
      if (row.BALANCE_NO && row.OWNER_CODE) {
        this.getPayObjPo(row);
        this.getBalanceDetailFun(row);
      }

      // 查询会员卡信息
      this.queryVipCartInfo(row, 2);

      // 查询装饰项目、装饰材料 Bill_NO
      this.queryBillItemPart(row);
      this.canCancel = false;

      this.balanceInfo = row;
    },
    // 补充工单字段
    async getOther(vin) {
      const res = await getOtherData(vin);
      this.$set(this.orderPartMenus[0].params.data, 'CERTIFICATE_NO', res.data.CERTIFICATE_NO);
      this.$set(this.orderPartMenus[0].params.data, 'CUSTOMER_LEVEL', res.data.CUSTOMER_LEVEL);
      this.$set(this.orderPartMenus[0].params.data, 'delivererHobbyContact', res.data.delivererHobbyContact);
      this.$set(this.orderPartMenus[0].params.data, 'HISTORY_REPAIR_AMOUNT', res.data.HISTORY_REPAIR_AMOUNT);
      this.$set(this.orderPartMenus[0].params.data, 'OWNER_CODE', res.data.OWNER_CODE);
      this.$set(this.orderPartMenus[0].params.data, 'traceTime', res.data.traceTime);
      this.$set(this.orderPartMenus[0].params.data, 'HISTORY_REPAIR_TIMES', res.data.HISTORY_REPAIR_TIMES);
    },
    // 装饰派工单查询装饰项目与材料
    async queryBillItemPart(row) {
      const billItemRes = await queryBillItemByBillNO(row.BILL_NO, { order: 'asc', ...this.dmsFunc });
      const billPartRes = await queryBillPartByBillNO(row.BILL_NO, { order: 'asc', ...this.dmsFunc });
      // const addRes = await queryRoAddItemByRoNO(row.BILL_NO, { order: 'asc', ...this.dmsFunc });
      // console.log(JSON.stringify(billItemRes), '装饰项目数据-----');
      // console.log(JSON.stringify(billPartRes), '装饰备件数据-----');
      // 给维修项目、维修材料列表赋值
      this.repairPartMenus[4].params.list = billItemRes.data;
      this.repairPartMenus[5].params.list = billPartRes.data;
      this.repairData4 = billItemRes.data;
      this.repairData5 = billPartRes.data;

      // 把维修组合列表传递给子组件
      this.receivablesMenus[1].params.repairListTotal = this.repairPartMenus;

      // 让tab值显示，后期优化
      let that = this;

      setTimeout(function() {
        that.repairPartName = '装饰材料';
        console.log('装饰材料');
      }, 500);
      setTimeout(function() {
        that.repairPartName = '装饰项目';
        console.log('装饰项目');
      }, 600);
    },
    // 查询会员卡信息 type 1 工单 2销售单与装饰派工单
    async queryVipCartInfo(row, type) {
      console.log(row, type, '查询会员卡信息');
      // queryVipInfoByRono // 根据工单号获取会员卡信息 roNo
      // queryVipInfoByBillNo orderType(状态：销售单2，装饰单3) 销售单号：salesPartNo，结算单号：balanceNo 装饰单号：billNo
      let fetchapi = type == 1 ? queryVipInfoByRono : queryVipInfoByBillNo;
      let params =
        type == 1
          ? {
              roNo: row.RO_NO
            }
          : {
              orderType: row.SALES_PART_NO ? 2 : 3,
              salesPartNo: row.SALES_PART_NO || '',
              billNo: row.BILL_NO || '',
              balanceNo: row.BALANCE_NO
            };

      let res = await fetchapi(params);

      if (res.resultCode == 200 && res.data.result != false) {
        console.log(res.data, '会员卡信息');
        // this.vipList.map(item => {
        //   item.initialValue = res.data[item.fieldName];
        // });
        // 拷贝结算写法 hxj 2020/2/5
        if (type == 1) {
          this.vipList.find(item => item.fieldName === 'vCardNo').initialValue = res.data.resultData.V_CARD_NO;
          this.vipList.find(item => item.fieldName === 'nManhaurDisRate').initialValue = (res.data.resultData.N_MANHAUR_DIS_RATE || 0) + '%';
          this.vipList.find(item => item.fieldName === 'nMaterialDisrate').initialValue = (res.data.resultData.N_MATERIAL_DISRATE || 0) + '%';
          this.vipList.find(item => item.fieldName === 'nPoint').initialValue = res.data.resultData.N_POINT || 0;
          this.vipList.find(item => item.fieldName === 'nRatioPoint').initialValue = (res.data.resultData.N_RATIO_POINT || 0) + '%';
          this.vipList.find(item => item.fieldName === 'nRatioScore').initialValue = res.data.resultData.N_RATIO_SCORE || 0;
          this.vipList.find(item => item.fieldName === 'nPointPer').initialValue = (res.data.resultData.N_POINT_PER || 0) + '%';

          this.vipList.find(item => item.fieldName === 'nValideAmt').initialValue = res.data.ReturnMemberInfo.nValideAmt;
          this.vipList.find(item => item.fieldName === 'nThisPoint').initialValue = res.data.ReturnMemberInfo.nThisPoint;
          this.vipList.find(item => item.fieldName === 'nCardPoint').initialValue = res.data.ReturnMemberInfo.nCardPoint;
          this.vipList.find(item => item.fieldName === 'nCardRecharge').initialValue = res.data.ReturnMemberInfo.nCardRecharge;
          this.vipList.find(item => item.fieldName === 'nMoneyRecharge').initialValue = res.data.ReturnMemberInfo.nMoneyRecharge;
        } else {
          this.vipList.find(item => item.fieldName === 'vCardNo').initialValue = res.data.ReturnMemberInfo.vCardNo;
          this.vipList.find(item => item.fieldName === 'nManhaurDisRate').initialValue = (res.data.ReturnMemberInfo.nManhaurDisRate || 0) + '%';
          this.vipList.find(item => item.fieldName === 'nMaterialDisrate').initialValue = (res.data.ReturnMemberInfo.nMaterialDisrate || 0) + '%';
          this.vipList.find(item => item.fieldName === 'nPoint').initialValue = res.data.resultData.N_POINT || 0;
          this.vipList.find(item => item.fieldName === 'nRatioPoint').initialValue = (res.data.ReturnMemberInfo.nRatioPoint || 0) + '%';
          this.vipList.find(item => item.fieldName === 'nRatioScore').initialValue = res.data.ReturnMemberInfo.nRatioScore;
          this.vipList.find(item => item.fieldName === 'nPointPer').initialValue = (res.data.ReturnMemberInfo.nPointPer || 0) + '%';
          this.vipList.find(item => item.fieldName === 'nValideAmt').initialValue = res.data.ReturnMemberInfo.nValideAmt;
          this.vipList.find(item => item.fieldName === 'nThisPoint').initialValue = res.data.ReturnMemberInfo.nThisPoint;
          this.vipList.find(item => item.fieldName === 'nCardPoint').initialValue = res.data.ReturnMemberInfo.nCardPoint;

          if (res.data.ReturnMemberInfo.discountWay == 90091001) {
            this.vipList.find(item => item.fieldName === 'nCardRecharge').initialValue = res.data.ReturnMemberInfo.nCardRecharge;
            this.vipList.find(item => item.fieldName === 'nMoneyRecharge').initialValue = 0;
          } else {
            this.vipList.find(item => item.fieldName === 'nCardRecharge').initialValue = 0;
            this.vipList.find(item => item.fieldName === 'nMoneyRecharge').initialValue = res.data.ReturnMemberInfo.nMoneyRecharge;
          }
        }
      }
    },
    // 维修项目查询
    async getLabourDetailFun(row) {
      const res = await getLabourDetail(row.OWNER_CODE, row.BALANCE_NO);
      console.log(res.data, '----测试----');
      // 将获得的数据传给维修项目
      this.repairPartMenus[0].params.list = res.data;
      console.log(1);
    },
    // 维修材料查询
    async getRoRepairPartByBalanceNoFun(row) {
      const res = await queryRoRepairPartByBalanceNo(row.OWNER_CODE, row.BALANCE_NO);
      // 将获得的数据传给维修材料
      this.repairPartMenus[1].params.list = res.data;
      console.log(2);
    },
    // 销售材料查询
    async getSalesPoFun(row) {
      const res = await querySalesPo(row.OWNER_CODE, row.BALANCE_NO);
      // 将获得的数据传给销售材料
      this.repairPartMenus[2].params.list = res.data;
      console.log(3);
    },
    // 附加项目查询
    async getAddPoFun(row) {
      const res = await getAddPo(row.OWNER_CODE, row.BALANCE_NO);
      // 将获得的数据传给销售材料
      this.repairPartMenus[3].params.list = res.data;
      console.log(4);
    },
    // 获取结算单明细
    async getBalanceDetailFun(row) {
      const res = await getBalanceDetail(row.OWNER_CODE, row.BALANCE_NO);
      console.log(JSON.stringify(res.data), '结算单明细');
      this.feesSettlementList.forEach(x => {
        if (!x.initialValue) {
          x.initialValue = res.data[x.fieldName];
        }
        if (x.fieldName === 'RO_NO' || x.fieldName === 'SALES_PART_NO' || x.fieldName === 'BILL_NO') {
          x.disabled = true;
        }
      });

      this.feesSettlementList[2].initialValue = row.BALANCE_NO;
      // 如果只有备件销售单，没有工单，工单信息为空
      console.log(res.data, '工单信息 2222222222222222');
      // if (row.SALES_PART_NO !== '' && (row.RO_NO === '' || row.RO_NO === null)) {
      //   this.orderPartMenus[0].params.data = {};
      // } else {
      //   this.orderPartMenus[0].params.data = res.data;
      // }
      this.orderPartMenus[1].params.data = res.data;
      this.otherInfoList.forEach(x => {
        // x.initialValue = res.data[x.fieldName];
        if (x.fieldName === 'PAY_TYPE_CODE') {
          x.initialValue = +res.data[x.fieldName] === 0 ? '' : +res.data[x.fieldName];
        } else if (x.fieldName === 'DISCOUNT_MODE_CODE' || x.fieldName === 'ARR_BALANCE' || x.fieldName === 'GUARANTOR' || x.fieldName === 'BG_TYPE') {
          x.initialValue = res.data[x.fieldName];
        } else {
          x.initialValue = res.data[x.fieldName] ? Number(res.data[x.fieldName]).toFixed(2) : '0.0';

          if (x.fieldName === 'RECEIVE_AMOUNT') {
            this.receiveAmount = x.initialValue;
          }
        }
      });
      // this.otherInfoList.find(item => item.fieldName === 'discountAmount').initialValue = res.data.NET_AMOUNT;

      this.balanceInfo = row;
    },
    // 实收
    async getPayObjPo(row) {
      const res = await queryPayObjPo(row.OWNER_CODE, row.BALANCE_NO);
      console.log(res, '实收');
      this.receivablesMenus[0].params.list = res.data;
      this.receivablesMenus[1].params.list = res.data;
      // let REAL_TOTAL_AMOUNT = 0;
      // let TAX_AMOUNT = 0;
      // let NET_AMOUNT = 0;
      // let SUB_OBB_AMOUNT = 0;
      // let RECEIVABLE_AMOUNT = 0;
      // let TAX = res.data[0].TAX;
      // res.data.forEach(x => {
      //   REAL_TOTAL_AMOUNT += x.REAL_TOTAL_AMOUNT;
      //   TAX_AMOUNT += x.TAX_AMOUNT;
      //   NET_AMOUNT += x.NET_AMOUNT;
      //   SUB_OBB_AMOUNT += x.SUB_OBB_AMOUNT;
      //   RECEIVABLE_AMOUNT += x.RECEIVABLE_AMOUNT;
      // });
      // this.otherInfoList.find(item => item.fieldName === 'TOTAL_AMOUNT').initialValue = REAL_TOTAL_AMOUNT;
      // this.otherInfoList.find(item => item.fieldName === 'TAX').initialValue = TAX;
      // this.otherInfoList.find(item => item.fieldName === 'TAX_AMOUNT').initialValue = TAX_AMOUNT;
      // this.otherInfoList.find(item => item.fieldName === 'NET_AMOUNT').initialValue = NET_AMOUNT;
      // this.otherInfoList.find(item => item.fieldName === 'SUB_OBB_AMOUNT').initialValue = SUB_OBB_AMOUNT;
      // this.otherInfoList.find(item => item.fieldName === 'CALC_RECEIVE_AMOUNT').initialValue = RECEIVABLE_AMOUNT;
    },
    async systemDefalutParams() {
      this.orderStatus = (await getSystemDefault({ itemCode: 8033 })).data;
    },
    // 取消结算
    async cancelBalanceCheck() {
      if (this.orderStatus == '10041001') {
        let roNo = this.balanceInfo.RO_NO;
        let params = {
          currentPage,
          pageSize,
          roNo
        };
        let res = await findNoList(params);
        if (res.resultCode === 200 && res.daia.records.size == 0) {
          this.cancelBalance();
        } else {
          this.$notify.success({ title: '提示信息', message: '委托书所关联的索赔单已成功上传至R3系统，不允许取消结算!' });
        }
      } else {
        this.cancelBalance();
      }
    },
    // 取消结算
    async cancelBalance() {
      if (true) {
        let vin = this.balanceInfo.VIN;
        let balanceNo = this.balanceInfo.BALANCE_NO;
        let roNo = this.balanceInfo.RO_NO;
        let salesPartNo = this.balanceInfo.SALES_PART_NO;
        let billNo = this.balanceInfo.BILL_NO;
        let params = {
          vin,
          balanceNo,
          salesPartNo,
          billNo,
          roNo
        };

        // 取消结算校验 Z-，S-单上传成功后不能取消（服务提供是否上传功能接口）
        if (roNo != '' && roNo != undefined) {
          // const res1 = await checkClaimStatusByRoNo({ roNo: this.balanceInfo.RO_NO });
          // if (res1.resultCode == 200) {
          //   if (res1.data == 'F') {
          //     this.$notify.warning({ title: '提示信息', message: '该工单已经索赔，不允许取消结算！' });
          //     return;
          //   }
          // }

          const res2 = await getStatusByRoNo({ roNo: this.balanceInfo.RO_NO });

          if (res2.resultCode == 200) {
            if (res2.data == 'F') {
              this.$notify.warning({ title: '提示信息', message: '当前工单已上传成功，无法进行取消操作！' });
              return;
            }
            if (res2.data == 'Error') {
              this.$notify.warning({ title: '提示信息', message: '取消结算与索赔服务接口异常，无法进行取消操作！' });
              return;
            }
          }
        }
        // 取消结算会员部分
        // const memberRes = await getMemberNOByNo({ roNo, salesPartNo, billNo, orderType: this.orderType });
        // if (memberRes.resultCode == 200) {
        //   if (memberRes.resultCode.resultCode == 200) {
        //     console.log(memberRes, 'memberRes');
        //     if (memberRes.data.data.dealCode != 200) {
        //       this.$notify.warning({ title: '提示信息', message: '会员优惠/优惠券返还失败，请联系管理员！' });
        //       return;
        //     }
        //   } else {
        //     this.$notify.warning({ title: '提示信息', message: '会员优惠/优惠券返还失败，请联系管理员！' });
        //     return;
        //   }
        // }

        // 取消结算订单部分
        let res = await cancelBalance(params);

        if (res.resultCode === 200) {
          if (roNo != '' && roNo != undefined) {
            await updateLastDate(this.balanceInfo.RO_NO); // 0- Z-更新上次保养日期
          }
          this.feesSettlementList[3].initialValue = res.data;
          this.canCancel = true;
          this.$notify.success({ title: '提示信息', message: '取消结算成功!' });

          let res1 = await cancelSettlementOther(params);
          if (res.resultCode === 200) {
          }
          var msg = '取消了[' + balanceNo + ']结算记录，原结算金额为' + this.receiveAmount + '元';

          // 取消结算调用重要日志
          await systemLogForCancelBalance({ msg: msg });
          /* 2020-04-13 将尊享悦享取消核销逻辑整合至结算单一事务 注销此处页面调用逻辑 */
          // 核销尊享悦享
          // if (roNo) {
          //   let data = {
          //     vin: vin,
          //     roNo: roNo,
          //     status: '0'
          //   };
          //   let ress = await pushHx(data);
          //   if (ress.data[0].TYPE == 'A') {
          //   } else if (ress.data[0].TYPE == 'E') {
          //     //  this.$notify.warning({ title: '提示信息', message: ress.data[0].Message });
          //   } else {
          //     this.$notify.success({ title: '提示信息', message: ress.data[0].Message });
          //   }
          // }
        }

        // 0- Z-更新上次保养日期
        // const res1 = await updateLastDate(this.RO_NO);

        // let res1 = await findNoList({params,currentPage: 1,pageSize: 500});
        // console.log(res1, 'asdasdsadasdasdasdads');
      } else {
        //  this.$notify.success({ title: '提示信息', message: '取消结算成功!' });
        this.$message({
          type: 'warning',
          message: '您没有取消结算的权限!'
        });
      }
    },
    // 取消
    async resetForm() {
      this.refreshView({ path: '/finance/repair/cancelFinance' });
    },
    tabClickHandle(tab) {},
    // 把相关组件回带的数据，赋值给表单元素
    syncFormListData(dataList) {
      // dataList 格式 -> [{ fieldName: 'xxx', value: 'xxx' }, ...]
      const formList = [...this.orderList, ...this.vownerList];
      const formFieldNames = formList.map(x => x.fieldName);
      dataList.forEach(x => {
        if (formFieldNames.includes(x.fieldName)) {
          let target = formList.find(k => k.fieldName === x.fieldName);
          if (!target) return;
          target.initialValue = x.value;
          if (target.fieldName === 'license' || target.fieldName === 'ownerName' || target.fieldName === 'salesDate') {
            target.disabled = true;
          } else {
            target.disabled = false;
          }
        }
      });

      console.log(dataList);
    },
    feesSettlementChangeHandle(val) {},
    otherInfoChangeHandle(val) {},
    // 打开工单选择页面
    openOrderNoHandle() {
      let that = this;
      this.feesSettlementList.forEach(x => {
        if (x.fieldName === 'RO_NO') {
          that.WorkSearch_rono = x.initialValue;
        }
        if (x.fieldName === 'SALES_PART_NO') {
          that.WorkSearch_partno = '';
        }
        this.orderType = 1; // 工单类型
        return;
      });
      this.orderNoDialogShow = true;
    },
    openPartNoHandle() {
      let that = this;
      this.feesSettlementList.forEach(x => {
        if (x.fieldName === 'RO_NO') {
          that.WorkSearch_rono = '';
        }
        if (x.fieldName === 'SALES_PART_NO') {
          that.WorkSearch_partno = x.initialValue;
        }
        this.orderType = 2; // 备件销售类型
        return;
      });
      this.saleOrderSelectVisible = true;
    },
    // 打开装饰派工工单选择页面
    async openBoutiqueNoHandle() {
      let that = this;
      this.feesSettlementList.forEach(x => {
        if (x.fieldName === 'BILL_NO') {
          that.WorkSearch_billno = x.initialValue;
        }
        return;
      });
      this.boutiqueOrderNoDialogShow = true;
    }
  }
};
</script>

<style lang="less" scoped>
.vehicle-details-wrap {
  position: relative;
  padding-bottom: @modulePadding;
  .box {
    border: 1px solid #ccc;
    padding-top: 15px;
    padding-right: 15px;
    border-radius: @borderRadius;
    margin-bottom: 20px;
    box-shadow: @boxShadow;
  }
  .left {
    position: absolute;
    left: 0;
    width: calc(100% - 300px);
    border: 1px solid @borderColor;
    border-radius: @borderRadius;
    box-shadow: @boxShadow;
    padding: @modulePadding;
    padding-left: 0;
  }
  .right {
    margin-left: calc(100% - 280px);
    border: 1px solid @borderColor;
    border-radius: @borderRadius;
    box-shadow: @boxShadow;
    padding: @modulePadding;
  }
  .choose-style {
    color: @primaryColor;
  }
}
</style>
